package com.youxin.chat.pay.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TResult;
import com.youxin.chat.pay.mapper.UserWalletMapper;
import com.youxin.chat.pay.model.UserWallet;
import com.youxin.chat.pay.service.UserWalletService;
import com.youxin.context.BaseContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * description: WalletHandlerInterceptor <br>
 * date: 2020/3/1 16:37 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Component
public class WalletHandlerInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(WalletHandlerInterceptor.class);

    @Resource
    private UserWalletService userWalletService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userNo = BaseContextHandler.getUserNo();
        logger.info("execute wallet interceptor " + userNo);
        if(!StringUtils.isEmpty(userNo)){
           int status =  userWalletService.getWalletStatus(userNo);
           if(status != 0){
               logger.error("获取用户状态失败,userNo={}",userNo);
               returnJson(response);
               return false;
           }
        }

        return super.preHandle(request, response, handler);
    }

    private void returnJson(HttpServletResponse response){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            writer = response.getWriter();
            TResult result =TResult.build(BaseResultCode.COMMON_FAIL,"您的帐号信息被冻结");
            writer.print(JSONObject.toJSONString(result));
        } catch (IOException e){
            logger.error("拉截器异常",e);
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}
